/*
 * Copyright(c)2018,2024,guowenmeng24@163.comAllrightsreserved.
 */
package com.bkhech.netty.rabbitmq;

import com.bkhech.netty.websocket.UserChannelSession;
import com.bkhech.pojo.netty.DataContent;
import com.bkhech.utils.JsonUtils;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;

/**
 * RabbitMessageConsumer
 *  消费者，消费广播的聊天消息
 *@author guowm
 *@date 2024/11/28
 */
@Slf4j
public class RabbitMQMessageConsumer extends DefaultConsumer {
    private final String exchangeName;

    /**
     * Constructs a new instance and records its association to the passed-in channel.
     *
     * @param channel the channel to which this consumer is attached
     * @param exchangeName 交换机名称
     */
    public RabbitMQMessageConsumer(Channel channel, String exchangeName) {
        super(channel);
        this.exchangeName = exchangeName;
    }

    /**
     * 重写消息配送方法
     * @param consumerTag 消息的标签（标识）
     * @param envelope  信封（一些信息，比如交换机路由等等信息）
     * @param properties 配置信息
     * @param body 收到的消息数据
     * @throws IOException
     */
    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

        String msg = new String(body);
        String exchange = envelope.getExchange();
        log.error("监听到来自mq的消息。exchange：{}，message：{}", exchange, msg);

        if (exchange.equalsIgnoreCase(exchangeName)) {
            DataContent dataContent = JsonUtils.jsonToPojo(msg, DataContent.class);
            assert dataContent != null;
            String senderId = dataContent.getChatMsg().getSenderId();
            String receiverId = dataContent.getChatMsg().getReceiverId();

            // 发送聊天信息给接收用户
            List<io.netty.channel.Channel> receiverChannels =
                    UserChannelSession.getMultiChannels(receiverId);
            if (!CollectionUtils.isEmpty(receiverChannels)) {
                UserChannelSession.sendToTarget(receiverChannels, dataContent);
            }

            // 同步聊天信息给自己其他设备
            String currentChannelId = dataContent.getExtend();
            List<io.netty.channel.Channel> senderChannels =
                    UserChannelSession.getMyOtherChannel(senderId, currentChannelId);
            if (!CollectionUtils.isEmpty(senderChannels)) {
                UserChannelSession.sendToTarget(senderChannels, dataContent);
            }

        }
    }
}